package routes

import (
	"embed"
	"io"
	"io/fs"
	"net/http"
	"time"

	"github.com/gorilla/mux"

	"skedule-backend/config"
	"skedule-backend/handlers"
	"skedule-backend/middleware"
	"skedule-backend/scheduler"
	"skedule-backend/service"
	"skedule-backend/storage"
)

// SetupRoutes 设置所有路由
func SetupRoutes(cfg *config.Config, embeddedDist embed.FS, scheduler *scheduler.Scheduler, authConfig *handlers.AuthConfig, taskStore *storage.TaskStore, logStore *storage.LogStore, executionService *service.TaskExecutionService) *mux.Router {
	router := mux.NewRouter()

	// 添加日志中间件（第一个，记录所有请求）
	router.Use(middleware.LoggingMiddleware)
	
	// 添加CORS中间件
	router.Use(middleware.CORS)

	// 创建处理器
	authHandler := handlers.NewAuthHandler(authConfig)
	wsHandler := handlers.NewWSHandler()
	
	// 设置WebSocket处理器到执行服务
	executionService.SetWSHandler(wsHandler)
	
	taskHandler := handlers.NewTaskHandler(scheduler, executionService)
	logHandler := handlers.NewLogHandler()
	settingsHandler := handlers.NewSettingsHandler(scheduler)

	// 设置API路由（需要认证）
	apiRouter := router.PathPrefix("/api").Subrouter()
	
	// 认证路由（不需要JWT）
	handlers.SetupAuthRoutes(apiRouter, authHandler)
	
	// WebSocket路由（不需要JWT，在连接后进行认证）
	handlers.SetupWSRoutes(apiRouter, wsHandler)

	// 需要JWT认证的路由
	protectedRouter := apiRouter.NewRoute().Subrouter()
	protectedRouter.Use(middleware.JWTMiddleware(authConfig.JWTSecret))

	// 设置各个模块的路由
	handlers.SetupTaskRoutes(protectedRouter, taskHandler)
	handlers.SetupLogRoutes(protectedRouter, logHandler)
	handlers.SetupSettingsRoutes(protectedRouter, settingsHandler)
	handlers.SetupProtectedAuthRoutes(protectedRouter, authHandler)

	// 设置静态文件路由（前端）
	setupStaticRoutes(router, embeddedDist)

	return router
}

// setupStaticRoutes 设置静态文件路由
func setupStaticRoutes(router *mux.Router, embeddedDist embed.FS) {
	// 获取嵌入的前端文件系统
	frontendFS, err := fs.Sub(embeddedDist, "dist/frontend/dist")
	if err != nil {
		panic("Unable to access embedded frontend files: " + err.Error())
	}

	// 静态文件服务
	fileServer := http.FileServer(http.FS(frontendFS))

	// 处理静态资源（CSS, JS, 图片等）
	router.PathPrefix("/assets/").Handler(fileServer)
	router.PathPrefix("/css/").Handler(fileServer)
	router.PathPrefix("/js/").Handler(fileServer)
	router.PathPrefix("/img/").Handler(fileServer)
	router.PathPrefix("/fonts/").Handler(fileServer)

	// 处理favicon和其他根级文件
	router.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		fileServer.ServeHTTP(w, r)
	})
		
	// SPA路由处理 - 所有未匹配的路由都返回index.html
	router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 如果是API请求，返回404
		if len(r.URL.Path) > 4 && r.URL.Path[:5] == "/api/" {
			http.Error(w, "API endpoint not found", http.StatusNotFound)
			return
		}
		
		// 否则返回index.html让前端路由处理
				w.Header().Set("Content-Type", "text/html; charset=utf-8")
		file, err := frontendFS.Open("index.html")
		if err != nil {
			http.Error(w, "Frontend not found", http.StatusNotFound)
				return
			}
		defer file.Close()

		http.ServeContent(w, r, "index.html", time.Time{}, file.(io.ReadSeeker))
	})
} 